import React, { useEffect, useMemo } from 'react';
import { Table, Button, Input, message, Popconfirm } from 'antd';
import { useDispatch, useSelector } from 'dva';
import { AsyncModal, FormPannel, Selection, SearchPannel } from 'src/components/index';

export const BOOK_STATUS = {
  NORMAL: 0, // 正常
  LOANED: 1, // 借出
  DISABLE: 2, // 禁用
};

export const BOOK_STATUS_MAP = {
  0: '正常',
  1: '借出',
  2: '禁用',
};

const Options = Object.entries(BOOK_STATUS_MAP).map(([value, label]) => ({
  label,
  value: parseInt(value),
}));

export default function Books() {
  const {
    books: { bookList },
    category: { list: categoryList },
  } = useSelector((state: any): any => {
    return state.present;
  });

  const categoryMap = useMemo(
    () =>
      (categoryList || []).reduce((memo, item) => {
        memo[item.id] = item.name;
        return memo;
      }, {}),
    [categoryList]
  );

  const dispatch = useDispatch();

  const getBookList = async (params?: any) => {
    try {
      await dispatch({ type: 'books/bookList', payload: params });
    } catch (error) {
      console.log(error);
    }
  };

  const handleEdit = async (row: any) => {
    const { result } = await AsyncModal.show({
      title: '编辑',
      content: ({ onFinish, destory }) => (
        <FormPannel
          columns={formColumns}
          onFinish={onFinish}
          showInModal
          hiddenResetBtn
          layout={{ column: 1 }}
          itemLayout={{ labelCol: { span: 4 }, wrapperCol: { span: 20 } }}
          addonButton={() => (
            <Button onClick={destory} style={{ marginRight: '10px' }}>
              取消
            </Button>
          )}
          initialValues={row}
        />
      ),
      footer: null,
      request: async (values: any) =>
        await dispatch({ type: 'books/editBook', payload: { ...values, id: row.id } }),
    });
    if (!result) return;
    message.success('添加成功');
    getBookList();
  };

  const loanCols = [
    { title: '借阅者', key: 'username', rules: [{ required: true, message: '请输入' }] },
    { title: '借阅者ID', key: 'id', rules: [{ required: true, message: '请输入' }] },
  ];

  // 借书
  const handleLoan = async (book: any) => {
    // 跟人关联
    const { result } = await AsyncModal.show({
      title: `借阅《${book.name}》`,
      content: ({ onFinish, destory }) => (
        <FormPannel
          columns={loanCols}
          onFinish={onFinish}
          showInModal
          hiddenResetBtn
          layout={{ column: 1 }}
          itemLayout={{ labelCol: { span: 6 }, wrapperCol: { span: 18 } }}
          addonButton={() => (
            <Button onClick={destory} style={{ marginRight: '10px' }}>
              取消
            </Button>
          )}
        />
      ),
      footer: null,
      request: async (values: any) => {
        const payload = {
          ...book,
          status: BOOK_STATUS.LOANED, // 修改为借出状态
          reader: {
            username: values.username,
            id: values.id,
          },
        };
        return await dispatch({ type: 'books/editBook', payload });
      },
    });
    if (!result) return;
    message.success('操作成功');
    getBookList();
  };

  // 还书
  const handleReturn = async (book: any) => {
    // 解除关联
    console.log(book);

    const { result } = await AsyncModal.show({
      title: `归还《${book.name}》`,
      content: ({ onFinish, destory }) => (
        <FormPannel
          columns={loanCols}
          onFinish={onFinish}
          showInModal
          hiddenResetBtn
          layout={{ column: 1 }}
          itemLayout={{ labelCol: { span: 6 }, wrapperCol: { span: 18 } }}
          addonButton={() => (
            <Button onClick={destory} style={{ marginRight: '10px' }}>
              取消
            </Button>
          )}
        />
      ),
      footer: null,
      request: async () => {
        const payload = {
          ...book,
          status: BOOK_STATUS.NORMAL, // 修改为借出状态
          reader: null,
        };
        return await dispatch({ type: 'books/editBook', payload });
      },
    });
    if (!result) return;
    message.success('操作成功');
    getBookList();
  };

  // 删除
  const handleDelete = async (book: any) => {
    // 解除关联
    console.log(book);
    try {
      await dispatch({ type: 'books/delBook', payload: book.id });
      message.success('删除成功');
      getBookList();
    } catch (error) {
      console.info(error);
    }
  };

  const formColumns = [
    { title: '书名', key: 'name', rules: [{ required: true, message: '请输入' }] },
    { title: '作者', key: 'author', rules: [{ required: true, message: '请输入' }] },
    { title: '编码', key: 'code', rules: [{ required: true, message: '请输入' }] },
    {
      title: '分类',
      key: 'category',
      rules: [{ required: true, message: '请输入' }],
      render: () => <Selection options={categoryList} labelName="name" valName="id" />,
    },
    {
      title: '状态',
      key: 'status',
      rules: [{ required: true, message: '请输入' }],
      render: () => <Selection options={Options} placeholder="请选择" />,
    },
    {
      title: '简介',
      key: 'summary',
      rules: [{ required: true, message: '请输入' }],
      render: () => {
        return <Input.TextArea placeholder="请输入" />;
      },
    },
  ];

  const columns = [
    { title: 'id', dataIndex: 'id' },
    { title: '书名', dataIndex: 'name' },
    { title: '作者', dataIndex: 'author' },
    { title: '编码', dataIndex: 'code' },
    { title: '分类', dataIndex: 'category', render: val => categoryMap[val] },
    { title: '状态', dataIndex: 'status', render: val => BOOK_STATUS_MAP[val] },
    { title: '借阅者', dataIndex: 'reader', render: val => val && val.username },
    { title: '借阅者ID', dataIndex: 'reader', render: val => val && val.id },
    { title: '简介', dataIndex: 'summary' },
    { title: '创建时间', dataIndex: 'createdAt' },
    {
      title: '操作',
      dataIndex: 'operation',
      render: (_val, row) => {
        return (
          <div>
            <Button
              type="primary"
              size="small"
              onClick={() => handleLoan(row)}
              disabled={row.status === BOOK_STATUS.LOANED}
            >
              借书
            </Button>
            <Button
              size="small"
              style={{ margin: '0 10px' }}
              onClick={() => handleReturn(row)}
              disabled={row.status !== BOOK_STATUS.LOANED}
            >
              还书
            </Button>
            <Button size="small" style={{ marginRight: '10px' }} onClick={() => handleEdit(row)}>
              编辑
            </Button>
            <Popconfirm
              title="确认要删除吗？"
              onConfirm={() => handleDelete(row)}
              disabled={row.status === BOOK_STATUS.LOANED}
            >
              <Button
                type="primary"
                danger
                size="small"
                disabled={row.status === BOOK_STATUS.LOANED}
              >
                删除
              </Button>
            </Popconfirm>
          </div>
        );
      },
    },
  ];

  const searchCols = [
    {
      title: 'ID',
      key: 'id',
    },
    {
      title: '书名',
      key: 'name',
    },
    {
      title: '作者',
      key: 'author',
    },
    {
      title: '分类',
      key: 'category',
      render: () => <Selection options={categoryList} labelName="name" valName="id" />,
    },
  ];

  const handleSearch = async (values: any) => {
    try {
      await dispatch({ type: 'books/bookList', payload: values });
    } catch (error) {
      console.log(error);
    }
  };

  const handleReset = () => {
    console.log('重置数据');
    getBookList();
  };

  useEffect(() => {
    getBookList();
    dispatch({ type: 'category/list' });
  }, []);

  const handleAdd = async () => {
    const { result } = await AsyncModal.show({
      title: '添加',
      content: ({ onFinish, destory }) => (
        <FormPannel
          columns={formColumns}
          onFinish={onFinish}
          showInModal
          hiddenResetBtn
          layout={{ column: 1 }}
          itemLayout={{ labelCol: { span: 4 }, wrapperCol: { span: 20 } }}
          addonButton={() => (
            <Button onClick={destory} style={{ marginRight: '10px' }}>
              取消
            </Button>
          )}
        />
      ),
      footer: null,
      request: async (values: any) => await dispatch({ type: 'books/addBook', payload: values }),
    });
    if (!result) return;

    message.success('添加成功');
    getBookList();
  };

  console.log('bookList', bookList);

  return (
    <div>
      <h1>图书列表</h1>
      <SearchPannel columns={searchCols} onSearch={handleSearch} onReset={handleReset} />
      <Button type="primary" onClick={handleAdd} style={{ marginBottom: '15px' }}>
        添加
      </Button>
      <Table columns={columns} dataSource={bookList} />
    </div>
  );
}
